package com.example.testandroid;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.Toast;

/**
 * 
 * @author Administrator
 * 
 */
public class MainActivity extends Activity implements OnPreparedListener,
		OnErrorListener, OnCompletionListener, OnSeekCompleteListener,
		OnBufferingUpdateListener, OnClickListener {
	private static final String TAG = "MainActivity";

	ImageButton btnPlayback;
	MediaPlayer mPlayer;// ����������
	SurfaceView mPreview;
	Toast mToast;
	MediaController mController;

	/**
	 * trigerMPlayer(int)�Ĳ��������´�����Դ���ָ������
	 */
	private static final int EXECUTE_PAUSE = 0;
	private static final int EXECUTE_PLAY = 1;
	private static final int EXECUTE_RELEASE = 2;
	private static final int EXECUTE_STOP = 3;
	private static final int EXECUTE_RESET = 4;

	private static final int STATE_INVALIDE = -1;
	private static final int STATE_PREPARED = 0;
	private static final int STATE_PLAYING = 1;
	private static final int STATE_PAUSE = 2;
	private static final int STATE_STOP = 3;
	private static final int STATE_UNINITIALIZE = 4;
	int mPlayerState = STATE_INVALIDE;

	private static final int WHAT_UPDATE_PLAYBACK_STATE = 1000;
	private static final int WHAT_SURFACE_CREATED = 1001;
	private static final int WHAT_SURFACE_DESTROY = 1002;

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT_UPDATE_PLAYBACK_STATE:
				updateUIState();
				break;
			case WHAT_SURFACE_DESTROY:
				executeMPlayer(EXECUTE_RELEASE);
				break;
			case WHAT_SURFACE_CREATED:
				// create mediaplayer
				mPlayer = new MediaPlayer();
				mPlayer.setDisplay(mPreview.getHolder());
				mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mPlayer.setOnPreparedListener(MainActivity.this);
				mPlayer.setOnErrorListener(MainActivity.this);
				mPlayer.setOnCompletionListener(MainActivity.this);
				mPlayer.setOnSeekCompleteListener(MainActivity.this);
				mPlayer.setOnBufferingUpdateListener(MainActivity.this);

				setPlayerState(STATE_INVALIDE);
				// init mediaplayer
				AssetManager AM = getAssets();
				AssetFileDescriptor afd;
				try {
					afd = AM.openFd("video.mp4");
					mPlayer.setDataSource(afd.getFileDescriptor(),
							afd.getStartOffset(), afd.getLength());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				mPlayer.prepareAsync();
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btnPlayback = (ImageButton) findViewById(R.id.btnPlayPause);
		mPreview = (SurfaceView) findViewById(R.id.SV);

		btnPlayback.setOnClickListener(this);

		SurfaceHolder holder = mPreview.getHolder();
		DisplayMetrics DM = getResources().getDisplayMetrics();
		System.out.println(String.format("width:%d,height:%d", DM.widthPixels,
				DM.heightPixels));
		holder.setFixedSize(DM.widthPixels, DM.heightPixels);
		holder.addCallback(new Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				mHandler.obtainMessage(WHAT_SURFACE_DESTROY).sendToTarget();

			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				mHandler.obtainMessage(WHAT_SURFACE_CREATED).sendToTarget();
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format,
					int width, int height) {
				// TODO Auto-generated method stub

			}
		});
		

	}

	@Override
	protected void onPause() {
		executeMPlayer(EXECUTE_STOP);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		executeMPlayer(EXECUTE_RELEASE);
		super.onDestroy();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		if (mp.getVideoHeight() != 0 && mp.getVideoWidth() != 0) {

			setPlayerState(STATE_PREPARED);
			showToast(R.string.vedio_prepare_ok);
		} else {
			setPlayerState(STATE_UNINITIALIZE);
			showToast(R.string.vedio_unsupport);
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		showToast(R.string.vedio_error_occured);
		executeMPlayer(EXECUTE_RESET);
		return true;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		mp.seekTo(0);
		executeMPlayer(EXECUTE_PLAY);
	}

	@Override
	public void onSeekComplete(MediaPlayer mp) {
		// TODO Auto-generated method stub
		showToast(R.string.vedio_seek_ok);
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub
		showToast(R.string.vedio_buffer_content);

	}

	private void showToast(int resId) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		mToast = Toast.makeText(this, getText(resId), Toast.LENGTH_SHORT);
		mToast.show();
	}

	/**
	 * 设置播放器的状态
	 * 
	 * @param state
	 */
	private void setPlayerState(int state) {
		mPlayerState = state;
		mHandler.obtainMessage(WHAT_UPDATE_PLAYBACK_STATE).sendToTarget();
	}

	/**
	 * 
	 * @param code
	 *            触发mediaplayer的操作代码
	 */
	private void executeMPlayer(int code) {
		switch (code) {
		case EXECUTE_PAUSE:
			if (mPlayer != null && mPlayer.isPlaying()) {
				mPlayer.pause();
			}
			setPlayerState(STATE_PAUSE);
			break;
		case EXECUTE_PLAY:
			if (mPlayer != null
					&& !mPlayer.isPlaying()
					&& (mPlayerState == STATE_PREPARED || mPlayerState == STATE_PAUSE)) {
				mPlayer.start();
			}
			setPlayerState(STATE_PLAYING);
			break;
		case EXECUTE_RELEASE:
			if (mPlayer != null) {
				mPlayer.stop();
				mPlayer.release();
				mPlayer = null;
			}
			setPlayerState(STATE_INVALIDE);
			break;
		case EXECUTE_STOP:
			if (mPlayer != null) {
				// MPlayer.stop();
				mPlayer.stop();
			}
			mPlayerState = STATE_STOP;
			setPlayerState(STATE_PAUSE);
			break;
		case EXECUTE_RESET:
			if (mPlayer != null) {
				mPlayer.reset();
			}
			setPlayerState(STATE_UNINITIALIZE);
			break;
		}
	}

	/**
	 * 根据播放状态，更新页面显示
	 */
	private void updateUIState() {
		switch (mPlayerState) {
		case STATE_INVALIDE:
			btnPlayback.setEnabled(false);
			btnPlayback.setImageResource(R.drawable.sl_play);
			break;
		case STATE_UNINITIALIZE:
			btnPlayback.setEnabled(false);
			btnPlayback.setImageResource(R.drawable.sl_play);
			break;
		case STATE_PREPARED:
			btnPlayback.setEnabled(true);
			btnPlayback.setImageResource(R.drawable.sl_play);
			break;
		case STATE_PLAYING:
			btnPlayback.setEnabled(true);
			btnPlayback.setImageResource(R.drawable.sl_pause);
			break;
		case STATE_PAUSE:
			btnPlayback.setEnabled(true);
			btnPlayback.setImageResource(R.drawable.sl_play);
			break;
		case STATE_STOP:
			btnPlayback.setEnabled(false);
			btnPlayback.setImageResource(R.drawable.sl_play);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		if (id == R.id.btnPlayPause) {
			if ((mPlayerState == STATE_PREPARED || mPlayerState == STATE_PAUSE)
					&& mPlayer != null) {
				executeMPlayer(EXECUTE_PLAY);
			} else if (mPlayerState == STATE_PLAYING && mPlayer != null) {
				executeMPlayer(EXECUTE_PAUSE);
			}

		}
	}
}
